package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	"fmt"
)

type SysTag struct {
	Id      int    `orm:"column(id);auto"`
	TagName string `orm:"column(tag_name);size(8)" description:"标签名称"`
}

func (t *SysTag) TableName() string {
	return "sys_tag"
}

func init() {
	orm.RegisterModel(new(SysTag))
}

// AddSysTag insert a new SysTag into database and returns
// last inserted Id on success.
func GetAllTag() ([]*SysTag,error) {
	o := orm.NewOrm()
	sysTags := make([]*SysTag,0)
	_, err := o.Raw("SELECT * from sys_tag").QueryRows(&sysTags)
	if err != nil {
		fmt.Println("select sys_tag error",err)
		return nil,err
	}
	return sysTags, nil
}

func GetTagByName(tagArr []string) string{
	tags := ""
	for k, v := range tagArr{
		o := orm.NewOrm()
		sysTag := &SysTag{}
		err := o.Raw("select id from sys_tag where tag_name = ?",v).QueryRow(sysTag);
		if err == nil {
			if k == (len(tagArr) - 1){
				tags += strconv.Itoa(sysTag.Id)
			}else{
				tags += strconv.Itoa(sysTag.Id) + ","
			}

		}else{
			sysTag.TagName = v
			id, err := o.Insert(sysTag)
			if err == nil {
				if(k == (len(tagArr) - 1)){
					tags += strconv.Itoa(int(id))
				}else{
					tags += strconv.Itoa(int(id)) + ","
				}
			}
		}
	}
	return tags
}

